document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone');
    const fileInput = document.getElementById('fileInput');
    const previewContainer = document.getElementById('previewContainer');
    const controls = document.getElementById('controls');
    const originalPreview = document.getElementById('originalPreview');
    const compressedPreview = document.getElementById('compressedPreview');
    const originalInfo = document.getElementById('originalInfo');
    const compressedInfo = document.getElementById('compressedInfo');
    const qualitySlider = document.getElementById('quality');
    const qualityValue = document.getElementById('qualityValue');
    const downloadBtn = document.getElementById('downloadBtn');
    const imagesList = document.getElementById('imagesList');
    const imagesGrid = document.getElementById('imagesGrid');

    let originalImage = null;
    let uploadedImages = []; // 存储上传的图片

    // 处理拖拽上传
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#0071e3';
    });

    dropZone.addEventListener('dragleave', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#ccc';
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#ccc';
        const files = Array.from(e.dataTransfer.files)
            .filter(file => file.type.startsWith('image/'));
        
        if (files.length > 20) {
            alert('最多只能选择20张图片！');
            return;
        }
        handleMultipleImages(files);
    });

    // 处理点击上传
    dropZone.addEventListener('click', () => {
        fileInput.click();
    });

    fileInput.addEventListener('change', (e) => {
        const files = Array.from(e.target.files);
        if (files.length > 20) {
            alert('最多只能选择20张图片！');
            return;
        }
        handleMultipleImages(files);
    });

    // 处理多图片上传
    function handleMultipleImages(files) {
        uploadedImages = files;
        imagesList.style.display = 'block';
        imagesGrid.innerHTML = '';
        
        files.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                const imageItem = createImagePreviewItem(e.target.result, file, index);
                imagesGrid.appendChild(imageItem);
            };
            reader.readAsDataURL(file);
        });

        if (files.length > 0) {
            handleImage(files[0]); // 显示第一张图片的预览
        }
    }

    // 创建图片预览项
    function createImagePreviewItem(src, file, index) {
        const div = document.createElement('div');
        div.className = 'image-item';
        div.innerHTML = `
            <img src="${src}" alt="预览图片">
            <button class="remove-btn" data-index="${index}">×</button>
            <div class="image-info">
                原始大小: ${formatFileSize(file.size)}
            </div>
        `;

        // 添加删除按钮事件
        div.querySelector('.remove-btn').addEventListener('click', (e) => {
            const index = parseInt(e.target.dataset.index);
            uploadedImages = uploadedImages.filter((_, i) => i !== index);
            refreshImagesList();
        });

        // 点击图片显示预览
        div.querySelector('img').addEventListener('click', () => {
            handleImage(file);
        });

        return div;
    }

    // 刷新图片列表
    function refreshImagesList() {
        imagesGrid.innerHTML = '';
        uploadedImages.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                const imageItem = createImagePreviewItem(e.target.result, file, index);
                imagesGrid.appendChild(imageItem);
            };
            reader.readAsDataURL(file);
        });

        if (uploadedImages.length === 0) {
            imagesList.style.display = 'none';
        }
    }

    // 处理图片压缩
    function handleImage(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            originalImage = new Image();
            originalImage.src = e.target.result;
            originalImage.onload = () => {
                // 显示原图
                originalPreview.src = originalImage.src;
                originalInfo.textContent = `大小: ${formatFileSize(file.size)}`;
                
                // 显示压缩后的图片
                compressImage();
                
                // 显示预览区域和控制区域
                previewContainer.style.display = 'flex';
                controls.style.display = 'block';
            };
        };
        reader.readAsDataURL(file);
    }

    // 压缩图片
    function compressImage() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.width = originalImage.width;
        canvas.height = originalImage.height;
        
        ctx.drawImage(originalImage, 0, 0);
        
        const quality = qualitySlider.value / 100;
        const compressedDataUrl = canvas.toDataURL('image/jpeg', quality);
        
        compressedPreview.src = compressedDataUrl;
        
        // 计算压缩后的实际大小
        const compressedSize = getBase64Size(compressedDataUrl);
        compressedInfo.textContent = `压缩后大小: ${formatFileSize(compressedSize)}`;
    }

    // 质量滑块改变时重新压缩
    qualitySlider.addEventListener('input', (e) => {
        qualityValue.textContent = `${e.target.value}%`;
        if (originalImage) {
            compressImage();
        }
    });

    // 下载按钮点击事件
    downloadBtn.addEventListener('click', () => {
        const link = document.createElement('a');
        link.download = 'compressed-image.jpg';
        link.href = compressedPreview.src;
        link.click();
    });

    // 工具函数：格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 工具函数：获取base64图片大小
    function getBase64Size(base64String) {
        const padding = base64String.endsWith('==') ? 2 : 1;
        return (base64String.length * (3/4)) - padding;
    }
}); 